package com.example.listener;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.User;
import com.example.enums.CodeEnum;
import com.example.exception.ServiceException;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 王鹤蒲
 * @Date 2023 11 09
 */

@Component
@Slf4j
public class UserExcelReadListener extends ExcelReadListener<User>{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean saveData() {
        System.out.println("-------------");
        List<User> userList=getDataList();
        log.debug(userList.toString());
        if(userList.isEmpty()){
            return false;
        }
        String createBy=userService.getCurrentLoginUser().getUserName();
        LocalDateTime createTime=LocalDateTime.now();
        String password=passwordEncoder.encode("abc123");
        userList.forEach(user -> {
            if(user.getUserName()==null||user.getEmail()==null||user.getPhonenumber()==null){
                throw new ServiceException(CodeEnum.File_IMPORT_ERROR.getCode(),CodeEnum.File_IMPORT_ERROR.getMsg());
            }
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<User>();
            lambdaQueryWrapper.eq(User::getUserName,user.getUserName()).or().eq(User::getEmail,user.getEmail()).or().eq(User::getPhonenumber,user.getPhonenumber());
            List<User> existingUserList=userMapper.selectList(lambdaQueryWrapper);
            if(existingUserList!=null){
                existingUserList.forEach((exitingUser)->{
                    if("0".equals(exitingUser.getDelFlag())){
                        throw new ServiceException(CodeEnum.File_IMPORT_ERROR.getCode(), CodeEnum.File_IMPORT_ERROR.getMsg());
                    }
                });
                }
            user.setPassword(password);
            user.setAvatar("http://localhost:8088/file/fc1ecf15cb564468a9c498eaff3e4ef0.jpg");
            user.setRole("ROLE_USER");
            if(user.getSex()==null){
                user.setSex("0");
            }
            if(user.getNickName()==null){
                user.setNickName("user_"+ IdUtil.getSnowflakeNextIdStr());
            }
            user.setCreateBy(createBy);
            user.setCreateTime(createTime);
        });
       return userMapper.insertBatch(userList)==userList.size();
    }
}
